package com.lc.luzhengtang.view.goodsdetail;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.webkit.WebView;


/**
 * Created by congl on 2017/6/30.
 */

public class NoticeTopWebView extends WebView {

    private static final String TAG = "NoticeTopWebView";

    private OnScrollChangedListener listener;
    private OnScrollToTopListener topListener;

    private boolean isCanScroll = true;

    public interface OnScrollChangedListener {
        void onScrollChanged(int l, int t, int oldl, int oldt);
    }

    public interface OnScrollToTopListener {
        void onScrollToTop(boolean isTop);
    }

    public void setOnScrollChangedListener(OnScrollChangedListener listener) {
        this.listener = listener;
    }

    public void setOnScrollToTopListener(OnScrollToTopListener listener) {
        this.topListener = listener;
    }

    public NoticeTopWebView(Context context) {
        super(context);
        init();
    }

    public NoticeTopWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public NoticeTopWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);

        if (topListener != null) {
            //WebView的总高度
            float webViewContentHeight = getContentHeight() * getScale();
            //WebView的现高度
            float webViewCurrentHeight = (getHeight() + getScrollY());
            System.out.println("webViewContentHeight=" + webViewContentHeight);
            System.out.println("webViewCurrentHeight=" + webViewCurrentHeight);
            if ((webViewContentHeight - webViewCurrentHeight) == 0) {
                topListener.onScrollToTop(true);
                System.out.println("WebView滑动到了底端");
            } else {
                topListener.onScrollToTop(false);
            }
        }

//        if (listener != null) {
//            listener.onScrollChanged(l, t, oldl, oldt);
//        }
//
//        if (topListener != null) {
//            topListener.onScrollToTop(t == 0 && oldt == 0);
//        }
    }

    public void setScroll(boolean isCanScroll) {
        this.isCanScroll = isCanScroll;
    }


    @Override
    public boolean onTouchEvent(MotionEvent arg0) {
        boolean b = !isCanScroll && super.onTouchEvent(arg0);
        Log.d(TAG, "--> onTouchEvent:b = " + b + ",isEnabled = " + isCanScroll);
        return b;
    }
}
